package com.lin.java.tool.send.sms.strategy.aliyun;

import cn.hutool.json.JSONUtil;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.google.gson.Gson;
import com.lin.java.tool.send.model.Sms;
import com.lin.java.tool.send.model.dto.SmsDTO;
import com.lin.java.tool.send.sms.SmsStrategy;
import darabonba.core.RequestConfiguration;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.extern.slf4j.Slf4j;

import java.time.Duration;

/**
 * @作者: 林江
 * @创建时间: 2024/4/12
 * @功能:
 */
@Slf4j
public class AlibabaSmsStrategy extends SmsStrategy {

    public AlibabaSmsStrategy(Sms sms) {
        this.sms = sms;
    }

    @Override
    protected Boolean sendSms(SmsDTO smsDTO) {
        log.info("阿里云发送短信，{}", JSONUtil.toJsonStr(sms));
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .phoneNumbers(String.join(",", smsDTO.getPhoneNums()))
                .signName(smsDTO.getSignName())
                .templateCode(smsDTO.getTemplate())
                .templateParam(new Gson().toJson(smsDTO.getVariableParam()))
                .requestConfiguration(RequestConfiguration.create())
                .build();

        log.info("发送成功，返回结果为：{}", new Gson().toJson(sendSmsRequest));
        return true;
//        try (AsyncClient client = getClient(sms)) {
//            // 异步发送
//            CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
//            // 处理发送有异常的处理
//            response.thenAccept(resp -> {
//                log.info("发送成功，返回结果为：{}", new Gson().toJson(resp));
//            }).exceptionally(e -> {
//                throw e;
//            });
//            return true;
//        } catch (Exception e) {
//           log.error("发送失败，失败的原因：{}", e.getMessage(), e);
//                throw new CustomSendException(SendEnum.SEND_FAIl);
//        }
    }

    private AsyncClient getClient() {
        StaticCredentialProvider provider = StaticCredentialProvider.create(
                Credential.builder()
                        .accessKeyId(sms.getAccessKeyId())
                        .accessKeySecret(sms.getAccessKeySecret())
                        .build()
        );

        // 配置客户端,Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        return AsyncClient.builder().region(sms.getRegion()) // Region ID
                .credentialsProvider(provider).overrideConfiguration(ClientOverrideConfiguration.create().setEndpointOverride(sms.getUrl()).setConnectTimeout(Duration.ofSeconds(60))).build();
    }

}
